package myJs.admin.limitManage

import myJs.CpLayer
import myJs.api.Api
import myJs.cps.{BootstrapTableCp, Style}
import myJs.cps.BootstrapTableCp.Column
import myJs.myPkg._
import myJs.tool.Pojo.{DateSearch, NumericSearch, TextSearch}
import org.scalajs.dom.{URLSearchParams, document}
import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import shared.pojo.Pojo.{EmailData, IdData, UserData}
import slinky.core.FunctionalComponent
import slinky.core.annotations.react
import slinky.core.facade.Hooks.{useEffect, useState}
import slinky.web.html._

import scala.collection.immutable.SeqMap
import myJs.Implicits._
import typings.csstype.csstypeStrings
import com.softwaremill.quicklens._
import myJs.tool.Tool

@react object Cp {

  val curPage = LimitManage

  type Props = Unit

  val component = FunctionalComponent[Props] { props =>

    val (datas, setDatas) = useState(List.empty[ujson.Obj])
    val (modifyShow, setModifyShow) = useState(false)
    val (modifyLimitShow, setModifyLimitShow) = useState(false)
    val (user, setUser) = useState(UserData())
    object FTool {

      def getShowValue(value: ujson.Value) = {
        if (value.myStr == "暂无") {
          "不限"
        } else value.myStr
      }

      def tbFmt(field: String) = (v: ujson.Value, row: ujson.Obj) => {
        field match {
          case "createTime" => span(getShowValue(v))()
          case "remainDays" => val str = s"${getShowValue(row("startTime"))} 至 ${getShowValue(row("endTime"))}"
            span(str)()
          case _ => span(v.myStr)()
        }
      }

      def comVFmt(fileTitle: String) = (v: ujson.Value, row: ujson.Obj) => {
        fileTitle match {
          case _ => v.myStr
        }
      }

      def userChange = (v: UserData) => {
        setUser(v)
      }

      def updateShow(id: String) = () => {
        Api.admin.getUserById(id).map { response =>
          val curUser = response.modify(_.password).setTo("")
          setUser(curUser)
          setModifyShow(true)
        }
        ()
      }

      def deleteData(id: String) = () => {
        val options = SwalOptions(title = "", text = "确定要删除此数据吗？", `type` = "warning", showCancelButton = true,
          showConfirmButton = true, confirmButtonClass = Tool.confirmButtonClass, confirmButtonText = "确定",
          closeOnConfirm = false, cancelButtonText = "取消", showLoaderOnConfirm = true,
          cancelButtonClass = Tool.cancelButtonClass)
        swal(options, () => {
          val request = IdData(id = id)
          Api.admin.deleteUserById(request).map { xhr =>
            refreshTableB().map { x =>
              swal(SwalOptions(title = "成功", text = "删除成功！", `type` = "success"))
            }
          }
        })
      }

      def refreshTableB = () => {
        Api.admin.getAllUser.map { response =>
          setDatas(response)
        }
      }

      def modifyShowChange = (v: Boolean) => {
        setModifyShow(v)
      }

      def modifyLimitShowChange = (v: Boolean) => {
        setModifyLimitShow(v)
      }

      def modifyLimitShow(id: String) = () => {
        Api.admin.getUserById(id).map { response =>
          val curUser = response.modify(_.password).setTo("")
          setUser(curUser)
          setModifyLimitShow(true)
        }
        ()
      }

      def operateFmt = (v: ujson.Value, row: ujson.Obj) => {
        span(
          a(style := Style(cursor = csstypeStrings.pointer),
            title := "重置密码", onClick := FTool.updateShow(row("id").myStr),
            span(
              em(className := "fa fa-key")
            )
          ),
          " ",
          a(style := Style(cursor = csstypeStrings.pointer),
            title := "删除", onClick := FTool.deleteData(row("id").myStr),
            span(
              em(className := "fa fa-close", "")
            )
          ),
          " ",
          a(style := Style(cursor = csstypeStrings.pointer),
            title := "设置权限", onClick := FTool.modifyLimitShow(row("id").myStr),
            span(
              em(className := "fa fa-edit", "")
            )
          )
        )()
      }


    }

    useEffect(() => {
      FTool.refreshTableB()
    }, List()
    )

    val map = SeqMap("name" -> "用户名", "fullName" -> "姓名", "unit" -> "单位", "email" -> "邮箱", "phone" -> "手机",
      "createTime" -> "创建时间", "remainTimes" -> "有效次数", "remainDays" -> "有效期限")
    val basicColumns = map.map { case (k, v) =>
      val searchKind = k match {
        case "createTime" => DateSearch
        case "remainTimes" => NumericSearch
        case _ => TextSearch
      }
      val fmt = FTool.tbFmt(k)
      val comVF = FTool.comVFmt(v)
      Column(field = k, title = v, operable = true, searchKind = searchKind, formatter = fmt, comVF = comVF)
    }.toList
    val operateColumn = Column(field = "operate", title = "操作", formatter = FTool.operateFmt, comVF = FTool.comVFmt(""))
    val columns = basicColumns :+ operateColumn

    CpLayer(title = curPage.titleStr)(
      div(className := "page-content",
        div(className := "page-bar",
          ul(className := "page-breadcrumb",
            li(
              i(className := "fa fa-table"), " ",
              a(href := "#", "权限管理")
            )
          )
        ),
        div(className := "row-fluid",
          div(className := "row",
            div(className := "col-md-12 col-sm-12",
              div(className := "portlet blue-madison box",
                div(className := "portlet-title",
                  div(className := "caption",
                    "权限管理"
                  )
                ),
                div(className := "portlet-body",
                  BootstrapTableCp(columns = columns, datas = datas, search = false),
                ),
                ResetPasswordCp(refreshTableB = FTool.refreshTableB, show = modifyShow,
                  showChange = FTool.modifyShowChange,
                  user = user, userChange = FTool.userChange),
                ModifyLimitCp(refreshTableB = FTool.refreshTableB, show = modifyLimitShow,
                  showChange = FTool.modifyLimitShowChange,
                  user = user, userChange = FTool.userChange)
              ),

            )

          )
        )
      )
    )

  }

}
